package com.stone.track

import android.os.Bundle
import android.view.View
import android.widget.SeekBar
import androidx.appcompat.app.AppCompatActivity
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.amap.api.maps.utils.overlay.MovingPointOverlay
import kotlinx.android.synthetic.main.activity_amap_track.*

class AMapTrackActivity : AppCompatActivity(), View.OnClickListener {

    companion object {
        const val TIME = 20
    }

    private lateinit var mMovingPointOverlay: MovingPointOverlay

    private lateinit var mAMap: AMap

    private lateinit var mCarMark: Marker

    /**
     * 全局坐标点
     */
    private val mPoints by lazy { readLatLng() }

    /**
     * 移动标记状态
     */
    private var mMoveMarkState = MoveMarkState.START_STATE

    /**
     * 正在绘制线 坐标集合
     */
    private val mPolyLinePoints = mutableListOf<LatLng>()

    /**
     * 单条绘制线 轨迹线
     */
    private lateinit var mPolyline: Polyline

    /**
     * 倍速 真实速度是 mSpeed - 1
     */
    private var mSpeed: Int = 2;

    private var mIndex: Int = mSpeed;


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_amap_track)
        mMapView.onCreate(savedInstanceState)

        mPlayImgCb.setOnClickListener(this)
        mStopImgBtn.setOnClickListener(this)
        mSpeedTv.setOnClickListener(this)
        initMovePointOverlay()
        initSeekBar()
    }

    /**
     * 初始化 移动
     */
    private fun initMovePointOverlay() {
        // 初始化地图
        mAMap = mMapView.map

        // 初始化地图位置
        val builder = LatLngBounds.builder()
        mPoints.forEach {
            builder.include(it)
        }
        val bounds = builder.build()
        mAMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 200))

        // 初始化点图标属性
        val markerOptions = MarkerOptions()
        // 放平
        markerOptions.isFlat = true
        // 锚点比例
        markerOptions.anchor(0.5f, 0.5f)
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_tour_record_car))
        mCarMark = mAMap.addMarker(markerOptions)
        mCarMark.position = mPoints[0]

        //绘制线初始化
        val polylineOptions = PolylineOptions()
        polylineOptions.visible(true)
            .setCustomTexture(BitmapDescriptorFactory.fromResource(R.mipmap.ic_tour_track))
            .useGradient(true)
            .width(20f)
        // 添加绘制轨迹线
        mPolyline = mAMap.addPolyline(polylineOptions)

        // 初始化移动
        mMovingPointOverlay = MovingPointOverlay(mAMap, mCarMark)
        // 设置总时长
        mMovingPointOverlay.setTotalDuration(1)
        // 设置点
        mMovingPointOverlay.setPoints(mPoints.subList(0, mIndex))


        // 监听器
        mMovingPointOverlay.setMoveListener { distance ->
            // 这两行一直要有
            mMovingPointOverlay.setVisible(true)
            mPolyline.isVisible = true

            println("mIndex==========$mIndex")
            if (distance == 0.0) {
                if (mPoints.size == mIndex) {
                    mMoveMarkState = MoveMarkState.STOP_STATE
                    runOnUiThread { mPlayImgCb.isChecked = false }
                }
            }
            mSeekBar.progress += 1
            val latLng = LatLng(
                mMovingPointOverlay.position.latitude,
                mMovingPointOverlay.position.longitude
            )
            mPolyLinePoints.add(latLng)
            mPolyline.points = mPolyLinePoints

        }
    }

    private fun initSeekBar() {
        mSeekBar.max = mPoints.size - 1
        mSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                // 重新开始时，不错处理
                if (progress == 0) {
                    return
                }
                // 拖动中时 实时修改 mMovingPointOverlay.的坐标数据
                mIndex = progress + mSpeed
                // 修改点位
                if (mIndex > mPoints.size) {
                    //当前为最后一个
                    mIndex = mPoints.size
                }
                // 重置 下标
                mMovingPointOverlay.resetIndex()
                mMovingPointOverlay.setPoints(mPoints.subList(progress, mIndex))
                mMovingPointOverlay.position = mPoints[progress]

                // 修改线
                clearPolyline()
                mPolyLinePoints.addAll(mPoints.subList(0, progress))
                mPolyline.points = mPolyLinePoints
                mMovingPointOverlay.startSmoothMove()
                mMoveMarkState =
                    if (mIndex == mPoints.size) MoveMarkState.STOP_STATE else MoveMarkState.MOVE_STATE
            }

            override fun onStartTrackingTouch(seekBar: SeekBar) {
                // 拖动开始时 停止 移动
                mPlayImgCb.isEnabled = false
                mPlayImgCb.isChecked = false
                mMovingPointOverlay.stopMove()
            }

            override fun onStopTrackingTouch(seekBar: SeekBar) {
                mPlayImgCb.isEnabled = true
                mPlayImgCb.isChecked = true
            }
        })
    }

    override fun onResume() {
        super.onResume()
        mMapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mMapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        mMapView.onSaveInstanceState(outState)
    }

    override fun onDestroy() {
        super.onDestroy()
        mMapView.onDestroy()
        mMovingPointOverlay.destroy()
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.mPlayImgCb -> {
                when (mMoveMarkState) {
                    MoveMarkState.START_STATE -> {
                        mMovingPointOverlay.startSmoothMove()
                        mMoveMarkState = MoveMarkState.MOVE_STATE
                    }
                    MoveMarkState.MOVE_STATE -> {
                        mMovingPointOverlay.stopMove()
                        mMoveMarkState = MoveMarkState.PAUSE_STATE
                    }
                    MoveMarkState.PAUSE_STATE -> {
                        mMovingPointOverlay.startSmoothMove()
                        mMoveMarkState = MoveMarkState.MOVE_STATE
                    }
                    MoveMarkState.STOP_STATE -> {
                        // 重新开始
                        clearPolyline()
                        mIndex = mSpeed
                        // 进度清零
                        mSeekBar.progress = 0
                        mMovingPointOverlay.position = mPoints[0]
                        mMovingPointOverlay.setPoints(mPoints.subList(0, mIndex))
                        mMovingPointOverlay.resetIndex()
                        mMovingPointOverlay.startSmoothMove()
                        mMoveMarkState = MoveMarkState.MOVE_STATE
                    }
                }
            }
            R.id.mSpeedTv -> {
                mSpeed = speedUp(mSpeed)
                mSeekBar.progress = mSeekBar.progress
            }
            R.id.mStopImgBtn -> {
                when (mMoveMarkState) {
                    MoveMarkState.STOP_STATE, MoveMarkState.MOVE_STATE, MoveMarkState.PAUSE_STATE -> {
                        mMovingPointOverlay.stopMove()
                        mSeekBar.progress = 0
                        clearPolyline()
                        clearCarMark()
                        mMovingPointOverlay.setVisible(false)
                        mPolyline.isVisible = false
                        mMoveMarkState = MoveMarkState.START_STATE
                        if (mPlayImgCb.isChecked) {
                            mPlayImgCb.isChecked = false
                        }
                    }
                    MoveMarkState.START_STATE -> {
                        return
                    }
                }
            }
        }
    }

    private fun speedUp(oldSpeed: Int): Int {
        val maxSpeed = 6;
        var i = oldSpeed + 1
        if (i > maxSpeed) {
            i = 2
        }
        runOnUiThread {
            if (i == 2) {
                mSpeedTv.text = "正常"
            } else {
                mSpeedTv.text = ("X${i - 1}")
            }
        }
        return i
    }

    /**
     * 清楚绘制线
     */
    private fun clearPolyline() {
        mPolyLinePoints.clear()
        mPolyline.points = mPolyLinePoints
    }

    private fun clearCarMark() {
        mCarMark.position = mPoints[0]
        mMovingPointOverlay.position = mPoints[0]
        mMovingPointOverlay.setPoints(null)
        mMovingPointOverlay.resetIndex()
    }

    private fun readLatLng(): MutableList<LatLng> {
        val points = mutableListOf<LatLng>()
        var i = 0
        while (i < coords.size) {
            points.add(LatLng(coords[i + 1], coords[i]))
            i += 2
        }
        return points
    }

    private val coords = doubleArrayOf(
        116.3499049793749,
        39.97617053371078,
        116.34978804908442,
        39.97619854213431,
        116.349674596623,
        39.97623045687959,
        116.34955525200917,
        39.97626931100656,
        116.34943728748914,
        39.976285626595036,
        116.34930864705592,
        39.97628129172198,
        116.34918981582413,
        39.976260803938594,
        116.34906721558868,
        39.97623535890678,
        116.34895185151584,
        39.976214717128855,
        116.34886935936889,
        39.976280148755315,
        116.34873954611332,
        39.97628182112874,
        116.34860763527448,
        39.97626038855863,
        116.3484658907622,
        39.976306080391836,
        116.34834585430347,
        39.976358252119745,
        116.34831166130878,
        39.97645709321835,
        116.34827643560175,
        39.97655231226543,
        116.34824186261169,
        39.976658372925556,
        116.34825080406188,
        39.9767570732376,
        116.34825631960626,
        39.976869087779995,
        116.34822111635201,
        39.97698451764595,
        116.34822901510276,
        39.977079745909876,
        116.34822234337618,
        39.97718701787645,
        116.34821627457707,
        39.97730766147824,
        116.34820593515043,
        39.977417746816776,
        116.34821013897107,
        39.97753930933358,
        116.34821304891533,
        39.977652209132174,
        116.34820923399242,
        39.977764016531076,
        116.3482045955917,
        39.97786190186833,
        116.34822159449203,
        39.977958856930286,
        116.3482256370537,
        39.97807288885813,
        116.3482098441266,
        39.978170063673524,
        116.34819564465377,
        39.978266951404066,
        116.34820541974412,
        39.978380693859116,
        116.34819672351216,
        39.97848741209275,
        116.34816588867105,
        39.978593409607825,
        116.34818489339459,
        39.97870216883567,
        116.34818473446943,
        39.978797222300166,
        116.34817728972234,
        39.978893492422685,
        116.34816491505472,
        39.978997133775266,
        116.34815408537773,
        39.97911413849568,
        116.34812908154862,
        39.97920553614499,
        116.34809495907906,
        39.979308267469264,
        116.34805113358091,
        39.97939658036473,
        116.3480310509613,
        39.979491697188685,
        116.3480082124968,
        39.979588529006875,
        116.34799530586834,
        39.979685789111635,
        116.34798818413954,
        39.979801430587926,
        116.3479996420353,
        39.97990758587515,
        116.34798697544538,
        39.980000796262615,
        116.3479912988137,
        39.980116318796085,
        116.34799204219203,
        39.98021407403913,
        116.34798535084123,
        39.980325006125696,
        116.34797702460183,
        39.98042511477518,
        116.34796288754136,
        39.98054129336908,
        116.34797509821901,
        39.980656820423505,
        116.34793922017285,
        39.98074576792626,
        116.34792586413015,
        39.98085620772756,
        116.3478962642899,
        39.98098214824056,
        116.34782449883967,
        39.98108306010269,
        116.34774758827285,
        39.98115277119176,
        116.34761476652932,
        39.98115430642997,
        116.34749135408349,
        39.98114590845294,
        116.34734772765582,
        39.98114337322547,
        116.34722082902628,
        39.98115066909245,
        116.34708205250223,
        39.98114532232906,
        116.346963237696,
        39.98112245161927,
        116.34681500222743,
        39.981136637759604,
        116.34669622104072,
        39.981146248090866,
        116.34658043260109,
        39.98112495260716,
        116.34643721418927,
        39.9811107163792,
        116.34631638374302,
        39.981085081075676,
        116.34614782996252,
        39.98108046779486,
        116.3460256053666,
        39.981049089345206,
        116.34588814050122,
        39.98104839362087,
        116.34575119741586,
        39.9810544889668,
        116.34562885420186,
        39.981040940565734,
        116.34549232235582,
        39.98105271658809,
        116.34537348820508,
        39.981052294975264,
        116.3453513775533,
        39.980956549928244
    )
}
